import {fetch} from '../../../utils/axios'
import {downExcel} from '../../../utils/common'

const state = {
  name: '服务列表',
  editdialog: false,
  id: null,
  search: '',
  totalItems: 0,
  items: [],
  OutterIpSource: {},
  loading: true,
  pagination: {},
  headers: [],
  etext: 'No Data',
  rowsPerPageItems: [10, 50, 100, { text: 'All', value: 100000 }],
  searchLabel: '服务名，内网IP，外网IP，URL，内网URL',
  status: {},
  type: {},
  env: {}
}

const mutations = {
  handlerService: (state) => {
    const { sortBy, descending, page, rowsPerPage } = state.pagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/service/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search,
      status: state.status.value,
      serviceType: state.type.value,
      env: state.env.value
    }).then((response) => {
      state.items = response.results
      state.totalItems = response.count
      state.loading = false
    }).catch((error) => {
      state.etext = error.response
    })
  },
  serviceDownload () {
    downExcel(state.headers, state.items)
  },
  openServiceEdit (state, payload) {
    state.id = payload.id
    state.editdialog = true
  },
  loadServiceFilters (state) {
    fetch('/service/service_filters/', {
    }).then((response) => {
      let res = JSON.parse(response)
      state.status.items = res.status
      state.type.items = res.type
      state.env.items = res.env
      state.OutterIpSource.items = res.OutterIpSource
    }).catch((error) => {
      state.etext = error.response
    })
  },
  loadServiceHeaders (state) {
    fetch('/getmodels/', {
      appname: 'service',
      modelname: 'service'
    }).then((response) => {
      state.headers = JSON.parse(response)
    }).catch((error) => {
      state.etext = error.response
    })
  }
}

const actions = {
  handlerService: ({commit}) => {
    state.loading = true
    commit('handlerService')
  },
  serviceSearch ({commit, state}) {
    state.loading = true
    commit('handlerService')
  },
  serviceDownload ({commit}) {
    commit('serviceDownload')
  },
  openServiceEdit ({commit}, payload) {
    commit('openServiceEdit', payload)
  },
  loadServiceFilters ({commit}) {
    commit('loadServiceFilters')
  },
  loadServiceHeaders ({commit}) {
    commit('loadServiceHeaders')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
